package com.fengziyu.lib_recyclerview_fzy

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.fengziyu.lib_recyclerview_fzy.databinding.ActivityRecyclerViewBinding
import com.fengziyu.lib_recyclerview_fzy.goods.GoodsAdapter
import com.fengziyu.lib_recyclerview_fzy.goods.GoodsViewModel
import com.fengziyu.lib_recyclerview_fzy.mvvm.BaseActivity

@Route(path = "/recyclerview/RecyclerViewActivity")
class RecyclerViewActivity : BaseActivity<GoodsViewModel>() {
    private lateinit var binding: ActivityRecyclerViewBinding
    private lateinit var goodsAdapter: GoodsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRecyclerViewBinding.inflate(layoutInflater)
        setContentView(binding.root)
        goodsAdapter = GoodsAdapter(
            onItemClick = {
                Toast.makeText(this , "商品描述:${it.goods_desc}" , Toast.LENGTH_SHORT).show()
            },
            onItemLongClick = {
                Toast.makeText(this , "价格:${it.goods_default_price}" , Toast.LENGTH_SHORT).show()
            }
        )
        binding.rv.layoutManager = GridLayoutManager(this , 2)
        binding.rv.adapter = goodsAdapter

        initData()
        /**
         * 左滑删除
         */
        val itemTouchHelper = ItemTouchHelper(object :ItemTouchHelper.SimpleCallback(0 , ItemTouchHelper.LEFT){
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder,
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                goodsAdapter.notifyItemRemoved(position)
                Toast.makeText(this@RecyclerViewActivity , "删除了第${position}个" , Toast.LENGTH_SHORT).show()
            }
        })
        itemTouchHelper.attachToRecyclerView(binding.rv)
    }

    private fun initData() {
        viewModel.getGoods(0,2,10)
        viewModel.goodsResponse.observe(this){
            if(it.code == 200){
                goodsAdapter.setGoodsList(it.data)
            }
        }
        viewModel.error.observe(this){
            Log.d("TAGA", "initData: 错误$it")
        }
    }

    override fun initViewModel(): GoodsViewModel {
        return ViewModelProvider(this)[GoodsViewModel::class.java]
    }
}